//
//  ListLatitudesViewController.m
//  PracticoDAW
//
//  Created by Juan Jose Alcazar Cobano on 29/04/13.
//  Copyright (c) 2013 Juan Jose Alcazar Cobano. All rights reserved.
//

#import "ListLatitudesViewController.h"
#import "Latitud.h"
#import <CoreLocation/CoreLocation.h>
#import "DetailsViewController.h"
#import "DejalActivityView.h"
#import "LoginViewController.h"

@interface ListLatitudesViewController ()

@end

@implementation ListLatitudesViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        UINavigationItem *navigationItem = [self navigationItem];
        [navigationItem setTitle:@"Latitudes"];
        
        UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] initWithTitle:@"Salir" style:UIBarButtonItemStyleDone target:self action:@selector(logout)];
        [navigationItem setRightBarButtonItem:logoutButton];
    }
    return self;
}

- (void)logout
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.28 green:0.69 blue:0.76 alpha:1.0];
        
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    
    responseData = [[NSMutableData alloc] init];
    allLatitudes = [[NSMutableArray alloc] init];
    
    //[self getLatitudes];
    [self createStaticDataList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([allLatitudes count] == 0) {
        return 0;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [allLatitudes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    Latitud *l = [allLatitudes objectAtIndex:[indexPath row]];
    
    // Calcula la direccion exacta
    /*
    CLLocation *locationLatitude = [[CLLocation alloc] initWithLatitude:[[l latitude] floatValue] longitude:[[l longitude] floatValue]];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:locationLatitude completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];        
                
        //NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
        NSString *street = [placemark.addressDictionary valueForKey:@"Street"];
        NSString *city = [placemark.addressDictionary valueForKey:@"City"];
    
        [[cell textLabel] setText:@"Hola"];
        [[cell detailTextLabel] setText:city];
        
        [[self tableView] reloadData];
    }];
    */
    [[cell textLabel] setText:[l idLatitud]];
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    DetailsViewController *detailViewController = [[DetailsViewController alloc] init];
    
    Latitud *l = [allLatitudes objectAtIndex:[indexPath row]];
    
    [detailViewController setLatitud:l];
    
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void)getLatitudes
{
    [DejalBezelActivityView activityViewForView:[[self navigationController] view]];
    
    NSString *urlFinal = [NSString stringWithFormat:@"http://150.214.188.47:81/WcfLatitude.svc/GetLatitudes?user='jesus'&dev='jesus'&token='d71a06a879d8788eb1012a521925d980c63d0f79'"];
    
    NSURL *url = [NSURL URLWithString:urlFinal];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    if ([httpResponse statusCode] == 200) {
        NSLog(@"Conexion finalizada con exito");
    } else {
        NSLog(@"Conexion finalizada con codigo de error %d", [httpResponse statusCode]);
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *e = nil;
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&e];
    
    if (jsonDictionary) {
        NSMutableArray *latitudes = [jsonDictionary objectForKey:@"d"];
        NSLog(@"Hay %d latitudes", [latitudes count]);
        
        for (NSDictionary *l in latitudes) {
            Latitud *lat = [[Latitud alloc] init];
            [lat setIdLatitud:[[l objectForKey:@"id"] stringValue]];
            [lat setLatitude:[[l objectForKey:@"latitud"] stringValue]];
            [lat setLongitude:[[l objectForKey:@"longitud"] stringValue]];
            [lat setUsuario:[l objectForKey:@"usuario"]];
            
            [allLatitudes addObject:lat];
        }
    }
    
    NSLog(@"%@", allLatitudes);
    
    [[self tableView] reloadData];
    
    [DejalBezelActivityView removeView];
    
    [responseData setLength:0];
}

- (void)createStaticDataList
{
    Latitud *lat = [[Latitud alloc] init];
    [lat setIdLatitud:@"5"];
    [lat setLatitude:@"37.375371"];
    [lat setLongitude:@"-5.986261"];
    [lat setUsuario:@"alcazar"];
    
    Latitud *lat2 = [[Latitud alloc] init];
    [lat2 setIdLatitud:@"7"];
    [lat2 setLatitude:@"37.360794"];
    [lat2 setLongitude:@"-5.986261"];
    [lat2 setUsuario:@"alcazar"];
    
    NSArray *objects = [NSArray arrayWithObjects:lat, lat2, nil];
    
    [allLatitudes addObjectsFromArray:objects];
    
    [[self tableView] reloadData];
    
    [DejalBezelActivityView removeView];
}

@end
